'use strict';

const Controller = require('egg').Controller;

class contrl extends Controller {
    async add(){
        const {ctx,app,service} = this;
        var title = ctx.request.body.title || "";
        if(!title){
            ctx.error(app.resCode.params);
        }else{
            try{
                let param = ctx.request.body;
                param.uid = ctx.session.userinfo._id;
                let res = await service.note.add(param);
                ctx.success(res);
            }catch(e){
                ctx.error(app.resCode.params,e.message || e);
            }
        }
    }
    async remove(){
        const {ctx,app,service} = this;
        let id = ctx.request.body.id || "";
        if(!id){
         ctx.error(app.resCode.params);
        }else{
             try{
                 let res = await service.note.remove(id);
                 ctx.success(res);
             }catch(e){
                 ctx.error(app.resCode.params,e.message || e);
             }
        }
    }
    async update(){
        const {ctx,app,service} = this;
        let param = ctx.request.body;
        let id = param.id;
        delete param.id;
        delete param.uid;
        if(!id){
            ctx.error(app.resCode.params);
        }else{
            try{
                let res = await service.note.update(id,param);
                ctx.success(res);
            }catch(e){
                ctx.error(app.resCode.params,e.message || e);
            }
        }
   }
   async list(){
    const {ctx,app,service} = this;
    let query = ctx.query;
    let uid = ctx.session.userinfo._id;
    try{
        let res = await service.note.list(query,uid);
        ctx.success(res);
    }catch(e){
        ctx.error(app.resCode.params,e.message || e);
    }
   }
   async info(){
    const {ctx,app,service} = this;
    let id = ctx.query.id;
    if(!id){
        ctx.error(app.resCode.params);
    }else{
        try{
            let res = await service.note.info(id);
            ctx.success(res);
        }catch(e){
            ctx.error(app.resCode.params,e.message || e);
        } 
    }
   }
   async groupByTags(){
       // 根据 tags  分组 group
       const {ctx,app,service} = this;
       let uid = ctx.session.userinfo._id;
       try{
           let res = await service.note.groupByTags(uid);
           ctx.success(res);
       }catch(e){
           ctx.error(app.resCode.params,e.message || e);
       }
   }
}

module.exports = contrl;